package cn.hello2018.sdk.token;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * Token验证--Guava缓存的使用
 * 使用流程：
 * String token = UUID.randomUUID().toString(); // 随机生成通用唯一识别码UUID
 * TokenCache.setKey(TokenCache.TOKEN_PREFIX + "", token); // 存储
 * String realToken = TokenCache.getValue(TokenCache.TOKEN_PREFIX + ""); // 读取
 *
 * @author jeymingwu
 * @date 2019/3/19 11:05
 */
public class TokenCache {

    public static final String TOKEN_PREFIX = "token_";
    private static Logger logger = LoggerFactory.getLogger(TokenCache.class);
    // LRU算法 12小时有效
    private static LoadingCache<String, String> loadingCache =
            CacheBuilder.newBuilder().initialCapacity(1000).maximumSize(10000).expireAfterAccess(12, TimeUnit.HOURS).build(new CacheLoader<String, String>() {
                // 默认数据加载实现
                // 取值时如key无对应值则调用
                @Override
                public String load(String s) throws Exception {
                    return "null";
                }
            });

    public static void setKey(String key, String value) {
        loadingCache.put(key, value);
    }

    public static String getValue(String key) {
        String value = null;
        try {
            value = loadingCache.get(key);
            if (!"null".equals(value)) {
                return value;
            }
        } catch (Exception e) {
            logger.error("localCache get erroe" + e);
        }
        return null;
    }
}
